<template>
  <div class="disease-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>疾病信息登记管理</span>
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
          >
            登记疾病
          </el-button>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总记录数</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-value text-warning">{{ stats.cured }}</div>
            <div class="stat-label">已治愈</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-value text-danger">{{ stats.uncured }}</div>
            <div class="stat-label">未治愈</div>
          </div>
        </el-card>
      </div>
      
      <!-- 搜索表单 -->
      <el-form
        :inline="true"
        :model="searchForm"
        class="search-form"
      >
        <el-form-item label="奶牛编号">
          <el-input
            v-model="searchForm.cattleNumber"
            placeholder="请输入奶牛编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="疾病名称">
          <el-input
            v-model="searchForm.diseaseName"
            placeholder="请输入疾病名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="治愈状态">
          <el-select
            v-model="searchForm.curedStatus"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="已治愈" value="已治愈" />
            <el-option label="未治愈" value="未治愈" />
          </el-select>
        </el-form-item>
        <el-form-item label="发病时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="cattleNumber" label="奶牛编号" width="120" />
        <el-table-column prop="diseaseName" label="疾病名称" width="150" />
        <el-table-column prop="onsetDate" label="发病时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.onsetDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="symptoms" label="症状" min-width="200" show-overflow-tooltip />
        <el-table-column prop="treatment" label="治疗方案" min-width="200" show-overflow-tooltip />
        <el-table-column prop="curedStatus" label="治愈状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.curedStatus === '已治愈' ? 'success' : 'warning'">
              {{ row.curedStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cureDate" label="治愈日期" width="120">
          <template #default="{ row }">
            {{ row.cureDate ? formatDate(row.cureDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="owner" label="登记人" width="100" v-if="userStore.isAdmin" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin || row.owner === userStore.username"
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin || row.owner === userStore.username"
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="奶牛编号" prop="cattleNumber">
          <el-select
            v-model="formData.cattleNumber"
            placeholder="请选择或输入奶牛编号"
            filterable
            allow-create
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="cattle in cattleList"
              :key="cattle.id"
              :label="cattle.id"
              :value="cattle.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input
            v-model="formData.diseaseName"
            placeholder="请输入疾病名称"
          />
        </el-form-item>
        <el-form-item label="发病时间" prop="onsetDate">
          <el-date-picker
            v-model="formData.onsetDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="症状" prop="symptoms">
          <el-input
            v-model="formData.symptoms"
            type="textarea"
            :rows="3"
            placeholder="请输入症状描述"
          />
        </el-form-item>
        <el-form-item label="治疗方案" prop="treatment">
          <el-input
            v-model="formData.treatment"
            type="textarea"
            :rows="3"
            placeholder="请输入治疗方案"
          />
        </el-form-item>
        <el-form-item label="治愈状态" prop="curedStatus">
          <el-select
            v-model="formData.curedStatus"
            placeholder="请选择治愈状态"
            style="width: 100%"
            @change="handleStatusChange"
          >
            <el-option label="未治愈" value="未治愈" />
            <el-option label="已治愈" value="已治愈" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.curedStatus === '已治愈'"
          label="治愈日期"
          prop="cureDate"
        >
          <el-date-picker
            v-model="formData.cureDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import {
  getDiseaseList,
  createDisease,
  updateDisease,
  deleteDisease,
  getDiseaseStats
} from '@/api/disease'
import { getCattleList } from '@/api/cattle'
import dayjs from 'dayjs'

const userStore = useUserStore()

const loading = ref(false)
const tableData = ref([])
const cattleList = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)
const dateRange = ref([])

const searchForm = reactive({
  cattleNumber: '',
  diseaseName: '',
  curedStatus: '',
  startDate: '',
  endDate: ''
})

const stats = reactive({
  total: 0,
  cured: 0,
  uncured: 0
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const formData = reactive({
  id: null,
  cattleNumber: '',
  diseaseName: '',
  onsetDate: '',
  symptoms: '',
  treatment: '',
  curedStatus: '未治愈',
  cureDate: '',
  remark: ''
})

const formRules = {
  cattleNumber: [
    { required: true, message: '请选择或输入奶牛编号', trigger: 'change' }
  ],
  diseaseName: [
    { required: true, message: '请输入疾病名称', trigger: 'blur' }
  ],
  onsetDate: [
    { required: true, message: '请选择发病时间', trigger: 'change' }
  ],
  symptoms: [
    { required: true, message: '请输入症状描述', trigger: 'blur' }
  ],
  curedStatus: [
    { required: true, message: '请选择治愈状态', trigger: 'change' }
  ]
}

const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑疾病记录' : '登记疾病')

// 获取列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.page,
      pageSize: pagination.size,
      ...searchForm
    }
    const res = await getDiseaseList(params)
    tableData.value = res.data.records || []
    pagination.total = res.data.total || 0
    fetchStats()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await getDiseaseStats(searchForm)
    Object.assign(stats, res.data)
  } catch (error) {
    console.error('获取统计失败', error)
  }
}

// 获取奶牛列表（用于下拉选择）
const fetchCattleList = async () => {
  try {
    const res = await getCattleList({ pageNo: 1, pageSize: 1000 })
    cattleList.value = res.data.records || []
  } catch (error) {
    console.error('获取奶牛列表失败', error)
  }
}

// 搜索
const handleSearch = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.cattleNumber = ''
  searchForm.diseaseName = ''
  searchForm.curedStatus = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  dateRange.value = []
  pagination.page = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pagination.size = val
  fetchData()
}

const handlePageChange = (val) => {
  pagination.page = val
  fetchData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDisease(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 如果已治愈但没有选择治愈日期，自动设置为今天
      if (formData.curedStatus === '已治愈' && !formData.cureDate) {
        formData.cureDate = dayjs().format('YYYY-MM-DD')
      }
      
      try {
        if (isEdit.value) {
          await updateDisease(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createDisease(formData)
          ElMessage.success('登记成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 状态变化
const handleStatusChange = (val) => {
  if (val === '已治愈' && !formData.cureDate) {
    formData.cureDate = dayjs().format('YYYY-MM-DD')
  } else if (val === '未治愈') {
    formData.cureDate = ''
  }
}

// 重置表单
const resetForm = () => {
  formData.id = null
  formData.cattleNumber = ''
  formData.diseaseName = ''
  formData.onsetDate = ''
  formData.symptoms = ''
  formData.treatment = ''
  formData.curedStatus = '未治愈'
  formData.cureDate = ''
  formData.remark = ''
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  fetchData()
  fetchCattleList()
})
</script>

<style scoped>
.disease-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-value.text-warning {
  color: #e6a23c;
}

.stat-value.text-danger {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

